import React from 'react'
import _ from 'lodash'
import { routes } from '@/router'
import { useLocation, matchRoutes, Navigate } from 'react-router-dom'

import { useSelector } from 'react-redux'
import { useAppDispatch } from '@/store'
import { infoAction, updateInfos } from '@/store/modules/userStore'

import type { TypeUserInfo } from '@/api/login/type'
import type { RootState } from '@/store'

interface BeforEachPropsType {
    children?: React.ReactNode
}

const BeforEach = (props: BeforEachPropsType) => {
    const location = useLocation()  // 当前 路由
    const matchs = matchRoutes(routes, location) // 路由数据
    const userInfo = useSelector((state: RootState) => state.userStore.infos)
    const userToken = useSelector((state: RootState) => state.userStore.token)
    const dispatch = useAppDispatch()
    const getUserInfo = async () => {
        const { payload } = await dispatch(infoAction())
        const { errcode, infos } = payload as TypeUserInfo
        if (errcode !== 0) return false
        dispatch(updateInfos(infos))
    }
    if (Array.isArray(matchs)) {
        const meta = matchs[matchs.length - 1].route.meta
        if (meta?.auth && _.isEmpty(userInfo)) {
            if (userToken) {
                getUserInfo()
            } else {
                return <Navigate to="/login"/>
            }

        }else if(Array.isArray(userInfo.permission) && !userInfo.permission.includes(meta!.auth as string)){
            return <Navigate to="/403"/>
        }
    }
    if(userToken && location.pathname === '/login'){
        return <Navigate to="/"/>
    }
    return (
        <>{props.children}</>
    )
}

export default BeforEach
